using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    [Header("敌人设置")]
    [SerializeField] private float moveSpeed = 3f;
    [SerializeField] private float detectionRange = 10f;
    [SerializeField] private float minDistanceToPlayer = 0.5f;

    private Transform playerTransform;
    private Rigidbody2D rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
    }
     private void FixedUpdate()
    {
        if (playerTransform == null) return;

        // 计算到玩家的距离
        Vector2 directionToPlayer = (playerTransform.position - transform.position);
        float distanceToPlayer = directionToPlayer.magnitude;

        // 如果在检测范围内且不太靠近玩家，则移动
        if (distanceToPlayer <= detectionRange && distanceToPlayer > minDistanceToPlayer)
        {
            // 标准化方向向量
            Vector2 moveDirection = directionToPlayer.normalized;
            
            // 移动敌人
            rb.velocity = moveDirection * moveSpeed;

            // 更新朝向（如果敌人有朝向的话）
            float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Euler(0, 0, angle);
        }
        else
        {
            // 如果太近了，就停止移动
            rb.velocity = Vector2.zero;
        }
    }
    private void OnDrawGizmosSelected()
    {
        // 在Scene视图中显示检测范围
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, detectionRange);
        
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, minDistanceToPlayer);
    }
  
    
    

}
